// 认证相关功能

// 认证状态变量
let isPremiumAuthenticated = false;
let authTimestamp = 0;
let passwordAttempts = 0;

// 检查认证状态
function checkAuthenticationStatus() {
    // 检查是否已认证且未过期（30分钟有效期）
    const validDuration = 30 * 60 * 1000; // 30分钟
    return isPremiumAuthenticated && (Date.now() - authTimestamp < validDuration);
}

// 确保所有函数在全局作用域中可用
window.checkAuthenticationStatus = checkAuthenticationStatus;
window.verifyPremiumPassword = verifyPremiumPassword;
window.showChangePasswordModal = showChangePasswordModal;
window.changePassword = changePassword;
window.showChangePasswordError = showChangePasswordError;
window.showChangePasswordSuccess = showChangePasswordSuccess;
window.closeChangePasswordModal = closeChangePasswordModal;

// 密码验证函数
function verifyPremiumPassword(callback) {
    // 检查是否已经认证且未过期
    if (checkAuthenticationStatus()) {
        callback(true);
        return;
    }
    
    const modal = document.getElementById('passwordModal');
    const passwordInput = document.getElementById('premiumPassword');
    const errorElement = document.getElementById('passwordError');
    const submitBtn = document.getElementById('submitPasswordBtn');
    const cancelBtn = document.getElementById('cancelPasswordBtn');
    
    // 检查元素是否存在
    if (!modal || !passwordInput || !errorElement || !submitBtn || !cancelBtn) {
        console.error('密码验证弹窗元素未找到');
        callback(false);
        return;
    }
    
    // 清空之前的输入和错误信息
    passwordInput.value = '';
    errorElement.textContent = '';
    
    // 显示弹窗
    modal.style.display = 'flex';
    
    // 聚焦到密码输入框
    setTimeout(() => passwordInput.focus(), 100);
    
    // 提交按钮点击事件
    const submitHandler = async () => {
        const password = passwordInput.value.trim();
        
        if (!password) {
            errorElement.textContent = '请输入密码';
            return;
        }
        
        // 使用后端API验证密码
        try {
            const response = await fetch('/api/password/verify', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    password: password,
                    client_id: clientId || 'web_client'
                })
            });
            
            const result = await response.json();
            
            if (result.success) {
                // 密码正确，设置认证状态
                passwordAttempts = 0;
                isPremiumAuthenticated = true;
                authTimestamp = Date.now();
                modal.style.display = 'none';
                
                // 添加成功日志
                if (typeof addLogEntry === 'function') {
                    addLogEntry('🔐 付费区验证成功，欢迎使用高级功能！', 'success');
                }
                
                callback(true);
            } else {
                // 密码错误
                passwordAttempts++;
                errorElement.textContent = `密码错误，还有${3 - passwordAttempts}次尝试机会`;
                errorElement.style.display = 'block';
                
                if (passwordAttempts >= 3) {
                    // 超过尝试次数限制
                    errorElement.textContent = '尝试次数过多，请稍后再试';
                    setTimeout(() => {
                        modal.style.display = 'none';
                        callback(false);
                    }, 2000);
                }
            }
        } catch (error) {
            console.error('密码验证请求失败:', error);
            // 网络错误时回退到本地验证
            errorElement.textContent = '网络连接失败，请检查连接后重试';
            errorElement.style.display = 'block';
        }
    };
    
    // 取消按钮点击事件
    const cancelHandler = () => {
        modal.style.display = 'none';
        callback(false);
    };
    
    // 回车键提交
    const keyHandler = (e) => {
        if (e.key === 'Enter') {
            submitHandler();
        }
    };
    
    // 添加事件监听器
    submitBtn.addEventListener('click', submitHandler);
    cancelBtn.addEventListener('click', cancelHandler);
    passwordInput.addEventListener('keyup', keyHandler);
    
    // 清理函数 - 移除事件监听器
    const cleanup = () => {
        submitBtn.removeEventListener('click', submitHandler);
        cancelBtn.removeEventListener('click', cancelHandler);
        passwordInput.removeEventListener('keyup', keyHandler);
    };
}

// 显示密码修改弹窗
function showChangePasswordModal() {
    const modal = document.getElementById('changePasswordModal');
    const currentPasswordInput = document.getElementById('modalCurrentPassword');
    const newPasswordInput = document.getElementById('modalNewPassword');
    const confirmPasswordInput = document.getElementById('modalConfirmPassword');
    const errorElement = document.getElementById('changePasswordError');
    const successElement = document.getElementById('changePasswordSuccess');
    
    // 清空所有输入和消息
    currentPasswordInput.value = '';
    newPasswordInput.value = '';
    confirmPasswordInput.value = '';
    errorElement.style.display = 'none';
    successElement.style.display = 'none';
    
    modal.style.display = 'flex';
    
    // 聚焦到当前密码输入框
    setTimeout(() => currentPasswordInput.focus(), 100);
}

// 修改密码函数
async function changePassword() {
    const currentPassword = document.getElementById('modalCurrentPassword').value.trim();
    const newPassword = document.getElementById('modalNewPassword').value.trim();
    const confirmPassword = document.getElementById('modalConfirmPassword').value.trim();
    const errorElement = document.getElementById('changePasswordError');
    const successElement = document.getElementById('changePasswordSuccess');
    
    // 隐藏之前的消息
    errorElement.style.display = 'none';
    successElement.style.display = 'none';
    
    // 验证输入
    if (!currentPassword) {
        showChangePasswordError('请输入当前密码');
        return;
    }
    
    if (!newPassword) {
        showChangePasswordError('请输入新密码');
        return;
    }
    
    if (newPassword.length < 4) {
        showChangePasswordError('新密码长度至少为4位');
        return;
    }
    
    if (newPassword !== confirmPassword) {
        showChangePasswordError('两次输入的新密码不一致');
        return;
    }
    
    if (currentPassword === newPassword) {
        showChangePasswordError('新密码不能与当前密码相同');
        return;
    }
    
    try {
        // 发送密码修改请求到API
        const response = await fetch('/api/password/change', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                current_password: currentPassword,
                new_password: newPassword,
                client_id: clientId || 'web_client'
            })
        });
        
        const result = await response.json();
        
        if (result.success) {
            showChangePasswordSuccess('密码修改成功！');
        } else {
            showChangePasswordError(result.message || '密码修改失败');
        }
    } catch (error) {
        console.error('密码修改请求失败:', error);
        showChangePasswordError('网络请求失败，请检查连接');
    }
}

// 显示密码修改错误
function showChangePasswordError(message) {
    const errorElement = document.getElementById('changePasswordError');
    errorElement.textContent = message;
    errorElement.style.display = 'block';
}

// 显示密码修改成功
function showChangePasswordSuccess(message) {
    const successElement = document.getElementById('changePasswordSuccess');
    const errorElement = document.getElementById('changePasswordError');
    
    errorElement.style.display = 'none';
    successElement.textContent = message;
    successElement.style.display = 'block';
    
    // 3秒后自动关闭弹窗
    setTimeout(() => {
        closeChangePasswordModal();
    }, 3000);
}

// 关闭密码修改弹窗
function closeChangePasswordModal() {
    const modal = document.getElementById('changePasswordModal');
    modal.style.display = 'none';
}
